//
//  MainViewController.swift
//  JJWeibo
//
//  Created by JJ on 15/8/31.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addChildViewControllers()
        
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        setFrameOfComposedButton()
    }
    
    private func addChildViewControllers() {
        
        //添加tabbar的自控制器
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }

    private func addChildViewController(vc:UIViewController,title:String,imageName:String) {
        
        //设置每个子控制器的样式
        vc.title=title
        vc.tabBarItem.image=UIImage(named:imageName)
        let nav=UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
    }
    
    //设置按钮的样式
    private func setFrameOfComposedButton(){
        let count=childViewControllers.count
        let w=tabBar.bounds.width/CGFloat(count)
        let rect=CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        composedButton.frame=CGRectOffset(rect, 2*w, 0)
        
    }
    
    private lazy var composedButton:UIButton={
        
        //添加中间的按钮
        let btn=UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
       self.tabBar.addSubview(btn)
        
       btn.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
   @objc private func clickComposedButton(){
    
    let vc:UIViewController
    
    if UserAccountViewModel.sharedUserAccount.userLogon{
        vc=ComposeViewController()
    }else{
        vc=BaseTableViewController()
    }
     let nav=UINavigationController(rootViewController: vc)
    presentViewController(nav, animated: true, completion: nil)
    }

}





